package com.lindroy.androidplayer.ui.knowledge

import android.os.Bundle
import android.view.View
import com.lindroy.androidplayer.base.BaseListFragment
import com.lindroy.androidplayer.databinding.FragmentKnowledgeArticleBinding
import com.lindroy.androidplayer.ui.adapter.KnowledgeArticleAdapter
import com.lindroy.androidplayer.ui.webview.WebViewFragment
import com.lindroy.androidplayer.utils.addSimpleDivider
import com.lindroy.androidplayer.utils.collectListWhenResumed
import com.lindroy.androidplayer.utils.orZero
import com.lindroy.androidplayer.viewmodels.KnowledgeArticleViewModel

/**
 * @author Lin
 * @date 2022/1/24
 * @function 体系-文章列表页面
 * @Description
 */
class KnowledgeArticleFragment :
    BaseListFragment<FragmentKnowledgeArticleBinding, KnowledgeArticleViewModel>() {

    private val cid by lazy { arguments?.getInt(KEY_ID).orZero() }

    //    private val adapter by lazy { KnowledgeArticleAdapter(viewLifecycleOwner) }
    private lateinit var adapter: KnowledgeArticleAdapter

    companion object {
        private const val KEY_ID = "id"

        @JvmStatic
        fun newInstance(id: Int) =
            KnowledgeArticleFragment().apply {
                arguments = Bundle().apply {
                    putInt(KEY_ID, id)
                }
            }
    }

    override fun FragmentKnowledgeArticleBinding.initView(savedInstanceState: Bundle?) {
        vm = mViewMode
        rvArticle.addSimpleDivider()
        adapter = KnowledgeArticleAdapter(viewLifecycleOwner)
        rvArticle.adapter = adapter.withFooter()
    }

    override fun FragmentKnowledgeArticleBinding.initListener() {
        mViewMode.setLayoutStateFlow(adapter.loadStateFlow)
//        viewLifecycleOwner.lifecycleScope.launchWhenResumed {
//            mViewMode.getKnowledgeArticle(cid).collect {
//                adapter.submitData(it)
//            }
//        }
        mViewMode.getKnowledgeArticle(cid).collectListWhenResumed(viewLifecycleOwner) {
            adapter.submitData(it)
        }
        mViewMode.itemClickLiveData.observe(viewLifecycleOwner) {
            WebViewFragment.start(
                this@KnowledgeArticleFragment,
                it.id,
                it.link,
                it.title,
                it.collect
            )
        }
    }

    override fun onRefresh() {
        adapter.refresh()
    }

    override fun onRetry(view: View) {
        adapter.refresh()
    }
}